package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"net/http"
	"reflect"
	"web_end/global/response"
)

// GetErrorMsg /* 获取自定义的错误信息
func GetErrorMsg(err error, rawObj any) string {
	// 获取对象的类型
	obj := reflect.TypeOf(rawObj)

	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if field, ok := obj.Elem().FieldByName(e.Field()); ok {
				msg := field.Tag.Get("msg")
				fmt.Println(msg)
				return msg
			}
		}
	}
	return ""
}

// HandleGrpcErrorToHttp /* 将grpc的状态码转成http状态码
func HandleGrpcErrorToHttp(err error, ctx *gin.Context) {
	if err != nil {
		if e, ok := status.FromError(err); ok {
			switch e.Code() {
			case codes.NotFound:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  e.Message(),
					"code": response.CodeNotFound,
				})
			case codes.Internal:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  response.MsgInternalError,
					"code": response.CodeInternalServerError,
				})
			case codes.Unavailable:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  response.MsgUnavailable,
					"code": response.CodeInternalServerError,
				})
			case codes.InvalidArgument:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  response.MsgParamsError,
					"code": response.CodeBadRequest,
				})
			case codes.AlreadyExists:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  e.Message(),
					"code": response.CodeAlreadyExist,
				})

			default:
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  response.MsgOtherError,
					"code": response.CodeOtherError,
				})
			}
			return
		}
	}
}
